package com.ruoyi.wx.service;

import java.net.InetAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson2.JSON;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.request.WxPaySendMiniProgramRedpackRequest;
import com.github.binarywang.wxpay.bean.request.WxPaySendRedpackRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRedpackQueryResult;
import com.github.binarywang.wxpay.bean.result.WxPaySendMiniProgramRedpackResult;
import com.github.binarywang.wxpay.bean.result.WxPaySendRedpackResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.RedpackService;
import com.github.binarywang.wxpay.service.WxPayService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.wx.domain.WxApp;
import com.ruoyi.wx.domain.WxMaForm;
import com.ruoyi.wx.domain.WxMpApp;
import com.ruoyi.wx.domain.WxPayOrderNotifyInfo;
import com.ruoyi.wx.domain.WxPayReturnInfo;

/**
 * 微信小程序服务
 * 
 * @author ruoyi
 */
@Component
public class WxMaPayService {
	
	@Autowired
	private WxPayService wxPayService;

	@Autowired
	private IWxAppService wxAppService;
	
	@Autowired
	private IWxMpAppService wxMpAppService;
	
	public WxPayReturnInfo wechatPay(WxMaForm wxMaForm) {
		WxPayConfig payConfig = wxAppService.getPayConfig(wxMaForm.getAppId());
        WxPayUnifiedOrderRequest wxPayUnifiedOrderRequest = new WxPayUnifiedOrderRequest();
        //用户在当前小程序中的唯一标识
        wxPayUnifiedOrderRequest.setOpenid(wxMaForm.getOpenId());
        //订单编号
        wxPayUnifiedOrderRequest.setOutTradeNo(wxMaForm.getTradeNo());
        //订单金额单位分
        wxPayUnifiedOrderRequest.setTotalFee(wxMaForm.getTotalFee());
        //商品名称
        wxPayUnifiedOrderRequest.setBody(wxMaForm.getBody());
        //获取本地IP
        wxPayUnifiedOrderRequest.setSpbillCreateIp(InetAddress.getLoopbackAddress().getHostAddress());
        //支付回调地址
        wxPayUnifiedOrderRequest.setNotifyUrl(wxMaForm.getNotifyUrl());
        try {
        	wxPayService.setConfig(payConfig);
			Object data = wxPayService.createOrder(wxPayUnifiedOrderRequest);
			return JSON.parseObject(JSON.toJSONString(data), WxPayReturnInfo.class);
		} catch (WxPayException e) {
			e.printStackTrace();
			throw new ServiceException("微信支付调起失败");
		}
	}
	
	public WxPaySendRedpackResult sendRedpack(WxMaForm wxMaForm, String appName) throws Exception {
		WxPayConfig payConfig = wxAppService.getPayConfig(wxMaForm.getAppId());
		WxApp app = wxAppService.getByAppid(wxMaForm.getAppId());
		WxMpApp mp = wxMpAppService.getWxMpAppByWxId(app.getWxId());
		
		//String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        wxPayService.setConfig(payConfig);
    	RedpackService redpackService = wxPayService.getRedpackService();
    	WxPaySendRedpackRequest request = new WxPaySendRedpackRequest();
    	request.setMchBillNo(wxMaForm.getTradeNo()); // 商户订单号
    	request.setReOpenid(wxMaForm.getOpenId()); // 用户的openid
    	if(StringUtils.isBlank(appName)){
    		request.setSendName(app.getAppName()); // 红包发送者名称
    	}else{
    		request.setSendName(appName); // 红包发送者名称
    	}
    	request.setTotalAmount(wxMaForm.getTotalFee());// 付款金额 限制 大于100 小于200*100，单位分
    	request.setTotalNum(1); // 红包发放人数
    	request.setWishing("密搭收益提现"); // 包祝福语
    	request.setActName("邀请好友活动"); // 活动名称
    	request.setRemark("邀请好友红包奖励"); // 备注
    	request.setSceneId("PRODUCT_2"); // 场景id
    	request.setWxAppid(mp.getAppId());
    	//request.setClientIp(ip);
    	return redpackService.sendRedpack(request);
	}
	
	public WxPaySendMiniProgramRedpackResult sendMiniProgramRedpack(WxMaForm wxMaForm) {
		WxPayConfig payConfig = wxAppService.getPayConfig(wxMaForm.getAppId());
        wxPayService.setConfig(payConfig);
    	RedpackService redpackService = wxPayService.getRedpackService();
    	WxPaySendMiniProgramRedpackRequest request = new WxPaySendMiniProgramRedpackRequest();
    	request.setMchBillNo(wxMaForm.getTradeNo()); // 商户订单号
    	request.setReOpenid(wxMaForm.getOpenId()); // 用户的openid
    	request.setSendName("晚趣"); // 红包发送者名称
    	request.setTotalAmount(wxMaForm.getTotalFee());// 付款金额 限制 大于100 小于200*100，单位分
    	request.setTotalNum(1); // 红包发放人数
    	request.setWishing("红包祝福"); // 包祝福语
    	request.setActName("红包活动"); // 活动名称
    	request.setRemark("红包奖励"); // 备注
    	request.setSceneId("PRODUCT_2"); // 场景id
    	try {
    		WxPaySendMiniProgramRedpackResult result = redpackService.sendMiniProgramRedpack(request);
    		result.setSign(request.getSign());
    		result.setNonceStr(request.getNonceStr());
    		return result;
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("微信红包发送失败");
		}
	}
	
	public WxPayRedpackQueryResult queryRedpack(WxMaForm wxMaForm) {
		WxPayConfig payConfig = wxAppService.getPayConfig(wxMaForm.getAppId());
        wxPayService.setConfig(payConfig);
    	RedpackService redpackService = wxPayService.getRedpackService();
    	try {
    		return redpackService.queryRedpack(wxMaForm.getTradeNo());
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("微信红包查询失败");
		}
	}
	
	public WxPayOrderNotifyInfo notifyOrder(String xmlData){
		WxPayOrderNotifyInfo notify = new WxPayOrderNotifyInfo();
        //微信支付服务
        try {
        	WxPayOrderNotifyResult result = WxPayOrderNotifyResult.fromXML(xmlData);
        	WxPayConfig payConfig = wxAppService.getPayConfig(result.getAppid());
        	wxPayService.setConfig(payConfig);
        	WxPayOrderNotifyResult notifyResult = wxPayService.parseOrderNotifyResult(xmlData);
        	String notifyResponse = WxPayNotifyResponse.success("回调成功");
        	notify.setNotifyResponse(notifyResponse);
        	String tradeNo = notifyResult.getOutTradeNo();
        	notify.setTradeNo(tradeNo);
        	return notify;
        } catch (WxPayException e) {
			e.printStackTrace();
			String notifyResponse = WxPayNotifyResponse.fail("回调失败");
			notify.setNotifyResponse(notifyResponse);
			return notify;
		}
	}

}
